import { NextResponse } from 'next/server';
import { query } from '@/utils/db';
import { RowDataPacket } from 'mysql2/promise';

/**
 * 政策详情API
 * GET /api/enterprise/policies/[id]
 */
export async function GET(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const id = params.id;
    
    if (!id || isNaN(Number(id))) {
      return NextResponse.json(
        { success: false, message: '无效的政策ID' },
        { status: 400 }
      );
    }
    
    // 查询政策详情
    const policyQuery = `
      SELECT 
        id, title, summary, content, source, publish_date, 
        original_url, category, tags, 
        key_points, requirements, created_at
      FROM enterprise_policies
      WHERE id = ?
    `;
    
    // 查询相关政策
    const relatedPoliciesQuery = `
      SELECT 
        p.id, p.title, p.summary, p.source, p.publish_date, 
        p.category, p.tags
      FROM enterprise_policy_relations r
      JOIN enterprise_policies p ON r.related_policy_id = p.id
      WHERE r.policy_id = ?
      UNION
      SELECT 
        p.id, p.title, p.summary, p.source, p.publish_date, 
        p.category, p.tags
      FROM enterprise_policy_relations r
      JOIN enterprise_policies p ON r.policy_id = p.id
      WHERE r.related_policy_id = ?
      LIMIT 5
    `;
    
    // 执行查询
    const [policyResult] = await query<RowDataPacket[]>(policyQuery, [id]);
    
    if (!policyResult) {
      return NextResponse.json(
        { success: false, message: '未找到指定政策' },
        { status: 404 }
      );
    }
    
    const relatedPolicies = await query<RowDataPacket[]>(relatedPoliciesQuery, [id, id]);
    
    // 处理政策数据
    const policy = {
      id: policyResult.id,
      title: policyResult.title || '',
      summary: policyResult.summary || '',
      content: policyResult.content || '',
      source: policyResult.source || '',
      publishDate: policyResult.publish_date ? 
        new Date(policyResult.publish_date).toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit'
        }).replace(/\//g, '-') : null,
      url: policyResult.original_url || '',
      category: policyResult.category || '',
      tags: policyResult.tags ? policyResult.tags.split(',') : [],
      keyPoints: (() => {
        try {
          return policyResult.key_points ? JSON.parse(policyResult.key_points) : [];
        } catch (err) {
          console.error('解析key_points失败:', err);
          return [];
        }
      })(),
      requirements: (() => {
        try {
          return policyResult.requirements ? JSON.parse(policyResult.requirements) : [];
        } catch (err) {
          console.error('解析requirements失败:', err);
          return [];
        }
      })(),
      createdAt: policyResult.created_at
    };
    
    // 处理相关政策数据
    const formattedRelatedPolicies = relatedPolicies.map(relatedPolicy => {
      return {
        id: relatedPolicy.id,
        title: relatedPolicy.title || '',
        summary: relatedPolicy.summary || '',
        source: relatedPolicy.source || '',
        publishDate: relatedPolicy.publish_date ? 
          new Date(relatedPolicy.publish_date).toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit'
          }).replace(/\//g, '-') : null,
        category: relatedPolicy.category || '',
        tags: relatedPolicy.tags ? relatedPolicy.tags.split(',') : []
      };
    });
    
    return NextResponse.json({
      success: true,
      policy,
      relatedPolicies: formattedRelatedPolicies
    });
  } catch (error) {
    console.error('获取政策详情失败:', error);
    return NextResponse.json(
      { success: false, message: '获取政策详情失败' },
      { status: 500 }
    );
  }
} 